<?php
namespace ZfcAdmin\Controller;
use Zend\Form\Form;
use Zend\Stdlib\ResponseInterface as Response;
use Zend\Stdlib\Parameters;
use Zend\Authentication\AuthenticationService;
use SanAuthWithDbSaveHandler\Storage\IdentityManagerInterface;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Session\Container;
use Zend\View\Model\JsonModel;
use ZfcUser\Model\TuserTable;
use ZfcUser\Model\Tuser;
use Zend\Cache\StorageFactory;
use ScnSocialAuth\Mapper\UserProviderInterface;
use Users\Model\AdminTable;
use Users\Model\RatesTable;

class AdminController extends AbstractActionController
{
	public function indexAction()
	{
		if($_POST){
			$viewModel=new viewModel();
			$viewModel->setTerminal(true);
		
			$table = $this->getServiceLocator()->get('Users\Model\AdminTable');
			$request = $this->getRequest();
			$admindetails = $table->checkadminLogin($request->getPost());
			$admindetails1=json_encode($admindetails,1);
			if(strlen($admindetails1)!=5){
				$user_session = new Container('user');
				$user_session['username']=$admindetails->name;
				//echo $user_session['username'];exit;
				$user_session->user_id=$admindetails->a_num;
				return $this->redirect()->toUrl('admin/rates');
			}else{
				return $this->redirect()->toUrl('admin?id=3');
			}
		}
		
		$user_session = new Container('user');
		$user_session['username']='';
	}
	public function adminLoginAction()
	{
	}
	public function adminLogoutAction()
	{
		$user_session = new Container('user');
		$user_session['username']='';
		$result = new JsonModel(array(					
			'output' 		=> 'success',
		));
		return $result;
	}
	public function ratesAction(){
		$user_session = new Container('user');
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];
		if(isset($user_session['username']) && $user_session['username']!=''){
			$result= new ViewModel(array(
					"baseUrl" 	 =>	$baseUrl,
			));
			return $result;
		}else{
			return $this->redirect()->toUrl($baseUrl.'/admin');
		}
	}
	public function ratesListAction(){
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];
		
		$aColumns = array('sno','Flag','AreaPrefix','CountryName','Preminum','Standerd','BillingCycle','status','sno');
		$table = $this->getServiceLocator()->get('Users\Model\RatesTable');	
		$total = $table->getAllRates();
		$paginator = $table->getratesGrid($aColumns,$_POST,true);	
		$result['rResult']=array();
		foreach($paginator as $results){
			$result['rResult'][]=$results;
		}		
		if(count($result)!=0){			
			$result['iTotal']=$total;
			$result['iFilteredTotal']=$total;
			$result['sEcho']=intval($_POST['sEcho']);			
			$sOutput = '{';
			$sOutput .= '"sEcho": '.$result['sEcho'].', ';
			$sOutput .= '"iTotalRecords": '.$result['iTotal'].', ';
			$sOutput .= '"iTotalDisplayRecords": '.$result['iFilteredTotal'].', ';
			$sOutput .= '"aaData": [ ';
			for($m=0;$m<count($result['rResult']);$m++)
			{	
			//echo '<pre>';
			//print_r($result['rResult']);exit;
				$sOutput .= "[";
				for ( $i=0 ; $i<count($aColumns) ; $i++ )
				{
					$output_item = $result['rResult'][$m]->$aColumns[$i];
					if($i=='0'){
						$output_item = '<input type="checkbox" name="check[]" id="check" value="'.base64_encode($result['rResult'][$m]->sno).'" />';		
					}
					if($i=='1'){
						$output_item = $result['rResult'][$m]->Flag;
					}
					if($i=='2'){
						$output_item = $result['rResult'][$m]->AreaPrefix;
					}
					if($i=='3'){
						$output_item = $result['rResult'][$m]->CountryName;
					}
					if($i=='4'){
						$output_item = $result['rResult'][$m]->Preminum;
					}
					if($i=='5'){
						$output_item = $result['rResult'][$m]->Standerd;
					}
					if($i=='6'){
						$output_item = rtrim($result['rResult'][$m]->BillingCycle,"'");
					}					
					if($i=='7'){
						$output_item = $result['rResult'][$m]->status;
					}
					if($i=='8'){
					$output_item = '<a href="'.$baseUrl.'/admin/edit-rates-admin?id='.$result['rResult'][$m]->sno.'" title="Edit" class="">Edit</a>';
					}
					if($aColumns[$i]=='state'){ 
						if($result['rResult'][$m]->is_active == 1) $output_item = 'Active';
						else $output_item = 'Deactive';
					}
					$sOutput .= '"'.str_replace('"', '\"', $output_item).'",';
				}
				$sOutput = substr_replace( $sOutput, "", -1 );
				$sOutput .= "],";
			}
			$sOutput = substr_replace( $sOutput, "", -1 );
			$sOutput .= '] }';			
		}else{
			$sOutput = '{';
			$sOutput .= '"aaData": [ ';
			$sOutput .= '"sEcho": '.$_POST['sEcho'].', ';
			$sOutput .= '"iTotalRecords": 0, ';
			$sOutput .= '"iTotalDisplayRecords": 0, ';
			$sOutput .= '] }';
		}	
		echo $sOutput;exit;
	}	
	public function addRatesAction(){					
		if(isset($_POST['hidsno']) && $_POST['hidsno']==""){
			if($_POST){
				$_POST = array_merge($_POST,array("image" =>$_FILES["file"]["name"]));
				if(isset($_FILES['file'])){
					$upload_dir = './public/uploads/';
					//$filename=md5(time().rand(0,2000));
					$filename=$_FILES["file"]["name"];
                    $temp_file = $upload_dir. $filename;
					if(!file_exists($temp_file)){
					move_uploaded_file($_FILES["file"]["tmp_name"], $temp_file);}
				}
			}
			$table = $this->getServiceLocator()->get('Users\Model\RatesTable');
			//$request = $this->getRequest();
			$data = $table->addCountry($_POST);
			if($data>0){
				return $this->redirect()->toUrl('rates');
			}
		}else if(isset($_POST['hidsno']) && $_POST['hidsno']!=""){
			if(isset($_FILES['file']['size'])){
				if($_FILES['file']['size']!="0"){
					$_POST = array_merge($_POST,array("image" =>$_FILES["file"]["name"]));
					$upload_dir = './public/uploads/';
					//$filename=md5(time().rand(0,2000));
					$filename=$_FILES["file"]["name"];
					$temp_file = $upload_dir. $filename;
					if(!file_exists($temp_file)){
					move_uploaded_file($_FILES["file"]["tmp_name"], $temp_file);}
				}else{
					$_POST = array_merge($_POST,array("image" => $_POST['imag']));
				}
			}
			$table = $this->getServiceLocator()->get('Users\Model\RatesTable');
			$updateRates=$table->addCountry($_POST);			
			if($updateRates>=0){
				return $this->redirect()->toUrl('rates');
			}			
		}
		if(isset($_GET['id']) && $_GET['id']!=""){
			$table = $this->getServiceLocator()->get('Users\Model\RatesTable');
			$getdtls=$table->getRatesdetails($_GET['id']);
			$viewModel = new ViewModel(array(			
				'editDetails'		=>	$getdtls,					
			));
			return $viewModel;
		}
	}
	public function deleteAllAction(){
		$table = $this->getServiceLocator()->get('Users\Model\RatesTable');
		$result = $table->deleteAllRates();
		return $this->redirect()->toUrl('rates');
	}
	public function editRatesAdminAction(){
			if($_POST){
				if(isset($_POST['country']) && $_POST['country']!=''){
					$table = $this->getServiceLocator()->get('Users\Model\RatesTable');
					$result = $table->updateRates($_POST);
					return $this->redirect()->toUrl('rates');
				}
			}
			if(isset($_GET['id'])){
				$table = $this->getServiceLocator()->get('Users\Model\RatesTable');
				$result = $table->editrates($_GET['id']);
				//echo '<pre>';
				//print_r($result);exit;
				$result= new ViewModel(array(
					"data" 	 =>	$result,
				));
				return $result;
			}
	}
	public function inactivateAction()
	{
		$ids='';
		$items = rtrim($_POST['items'],",");
		$newItems = '';
		$itemsArray = explode(',',$items);
		foreach($itemsArray as $itemsValues)
		{
			$newItems.= base64_decode($itemsValues).',';
		}
		$id = rtrim($newItems,",");
		$idds=explode(',',$id);
		for($i=0;$i<count($idds);$i++){
			$ids .= "'".$idds[$i]."'".",";
		}
		$tIds = rtrim($ids,",");
		if(isset($_POST['type'])){
			if($_POST['type']=='rates'){
				$table = $this->getServiceLocator()->get('Users\Model\RatesTable');
				$result = $table->changeStatus($tIds,0);
			}
		}
		$result = new JsonModel(array(
			'total' => $result,
		));	
		$result->setTerminal(true);
		return $result; 
	}
	public function activateAction()
	{
		$ids='';
		$items = rtrim($_POST['items'],",");
		$newItems = '';
		$itemsArray = explode(',',$items);
		foreach($itemsArray as $itemsValues)
		{
			$newItems.= base64_decode($itemsValues).',';
		}
		$user_id = rtrim($newItems,",");
		$userids=explode(',',$user_id);
		for($i=0;$i<count($userids);$i++){
			$ids .= "'".$userids[$i]."'".",";
		}
		$id = rtrim($newItems,",");
		$idds=explode(',',$id);
		for($i=0;$i<count($idds);$i++){
			$ids .= "'".$idds[$i]."'".",";
		}
		$tIds = rtrim($ids,",");
		if(isset($_POST['type'])){
			if($_POST['type']=='rates'){
				$table = $this->getServiceLocator()->get('Users\Model\RatesTable');
				$result = $table->changeStatus($tIds,1);
			}
		}
		$result = new JsonModel(array(
			'total' => $result,
		));	
		$result->setTerminal(true);
		return $result; 
	}
	public function deleteSelectedAction()
	{
		$ids='';
		$items = rtrim($_POST['items'],",");
		$newItems = '';
		$itemsArray = explode(',',$items);
		foreach($itemsArray as $itemsValues)
		{
			$newItems.= base64_decode($itemsValues).',';
		}
		$user_id = rtrim($newItems,",");
		$userids=explode(',',$user_id);
		for($i=0;$i<count($userids);$i++){
			$ids .= "'".$userids[$i]."'".",";
		}
		$id = rtrim($newItems,",");
		$idds=explode(',',$id);
		for($i=0;$i<count($idds);$i++){
			$ids .= "'".$idds[$i]."'".",";
		}
		$tIds = rtrim($ids,",");
		if(isset($_POST['type'])){
			if($_POST['type']=='ratesdel'){
				$table = $this->getServiceLocator()->get('Users\Model\RatesTable');
				$result = $table->deleteRates($tIds);	
			}
		}
		$results = new JsonModel(array(
			'total' => $result,
		));	
		$results->setTerminal(true);
		return $results; 
	}
	public function bulkUpdatesAction(){
		return new viewModel();
	}
	public function csvFileUploadAction(){	
		if(isset($_FILES) && $_FILES['file_name']!=""){
			$fileName=$_FILES['file_name']['name'];
			move_uploaded_file($_FILES['file_name']['tmp_name'],'public/CsvData/'.$fileName);
			include('public/Excel/excel_reader.php');
			$data = new \Spreadsheet_Excel_Reader('public/CsvData/'.$fileName);			
			$table = $this->getServiceLocator()->get('Users\Model\DratesTable');		
			foreach($data->sheets[0]['cells'] as $results){
				$Success_status=$table->addRates($results);
			}
			return $this->redirect()->toUrl('rates');
		}else{
			echo "error"; 
		}
	
	}
}